/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.zzdt4j.core.executor.support.adpter;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.zzdt4j.common.api.DynamicThreadPoolAdapter;
import cn.zzdt4j.common.extension.spi.ServiceLoaderRegistry;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Dynamic thread-pool adapter choose.
 *
 * @author by <a href="mailto:ligang941012@gmail.com">gang.Li</a>
 * @since 2023/10/20 11:40
 */
public class DynamicThreadPoolAdapterChoose {

    private static final List<DynamicThreadPoolAdapter> DYNAMIC_THREAD_POOL_ADAPTERS = new ArrayList<>();

    public static boolean match(Object executor) {
        return DYNAMIC_THREAD_POOL_ADAPTERS.stream().anyMatch(each -> each.match(executor));
    }

    public static ThreadPoolExecutor unwrap(Object executor) {
        return parser(executor).map(each -> each.unwrap(executor)).orElse(null);
    }

    public static void replace(Object executor, Executor dynamicThreadPoolExecutor) {
        parser(executor).ifPresent(each -> each.replace(executor, dynamicThreadPoolExecutor));
    }

    private static Optional<DynamicThreadPoolAdapter> parser(Object executor) {
        return DYNAMIC_THREAD_POOL_ADAPTERS.stream().filter(each -> each.match(executor)).findFirst();
    }

    static {
        DYNAMIC_THREAD_POOL_ADAPTERS.add(new ThreadPoolTaskExecutorAdapter());
        loadCustomerAdapter();
    }

    private static void loadCustomerAdapter() {
        ServiceLoaderRegistry.register(DynamicThreadPoolAdapter.class);
        final Collection<DynamicThreadPoolAdapter> singletonServiceInstance = ServiceLoaderRegistry.getSingletonServiceInstances(DynamicThreadPoolAdapter.class);
        if (CollUtil.isEmpty(singletonServiceInstance)) {
            return;
        }
        for (DynamicThreadPoolAdapter instance : singletonServiceInstance) {
            if (ObjectUtil.isNotNull(instance)) {
                DYNAMIC_THREAD_POOL_ADAPTERS.add(instance);
            }
        }
    }
}
